<?php
  
  require_once(ROOT_PATH.'ty/DataBaseDao.php');
  class CategoryService extends dataBaseDao{
      
      public function getAllCategoryList(){
          return $this->getCategorysByParentId(array(), 0);
      }
      
      private function getCategorysByParentId($cateList, $parentId){
          $list = $this->getCategoryListByParentId($parentId);
          if(count($list) <= 0){
              return $cateList;
          }

          foreach($list as $k=>$v){
              array_push($cateList, $v);
              $cateList = $this->getCategorysByParentId($cateList, $v['cate_id']);
          }
          
          return $cateList;
      }
      
      public function saveCategory($cateInfo){
          if(empty($cateInfo)){
              return false;
          }
          
          $sql = "insert into news_category(cate_title,is_show_index,parent_id,open_news,flag,order_no) ";
          $sql .= " values('".$cateInfo['cate_title']."',".$cateInfo['is_show_index'].",".$cateInfo['parent_id'].",".$cateInfo['open_news'];
          $sql .= ",".$cateInfo['flag'].",".$cateInfo['order_no'].")";
          return $this->getDb()->query($sql);
      }
      
      public function updateCategory($cateInfo){
          if(empty($cateInfo)){
              return false;
          }
          
          $sql = "update news_category set ";
          foreach($cateInfo as $k=>$v){
              if($k == 'cate_id') continue;
              $sql .= " $k='$v',";
          }
          $sql = substr($sql, 0, strlen($sql)-1);
          $sql .= " where cate_id=".$cateInfo['cate_id'];
          return $this->getDb()->query($sql);
      }
      
      public function buildCateOptionHtml($selectId){
          return $this->buildOptionHtml('', '0', $selectId);
      }
      
      private function buildOptionHtml($html, $parentId, $selectId, $layer = 0){
          $list = $this->getCategoryListByParentId($parentId);
          if(count($list) <= 0){
              return $html;
          }
          
          $pre = '';
          for($i = 0; $i < $layer; $i++){
             $pre .= '&nbsp;&nbsp;';
          }
          
          foreach($list as $k=>$v){
              if($selectId == $v['cate_id']){
                  $html .= '<option value='.$v['cate_id'].' selected >'.$pre.$v['cate_title'].'</option>';
              }else{
                  $html .= '<option value='.$v['cate_id'].' >'.$pre.$v['cate_title'].'</option>';
              }
              $html = $this->buildOptionHtml($html, $v['cate_id'], $selectId, $layer+1);
          }
          return $html;
      }
      
      private function getCategoryListByParentId($parentId){
          $sql = "select a.*,b.cate_title parent_title from news_category a left join news_category b on b.cate_id=a.parent_id ";
          $sql .= " where a.parent_id=".strval($parentId)." order by order_no asc ";
          
          return $this->getDb()->fetchRows($sql);
      }
      
      
  }
  
?>
